<!--SMT站位表 导入-->
<template>
  <el-dialog
    width="50%"
    top="5vh"
    :title="title"
    custom-class="smtStandDialog"
    append-to-body
    v-if="showImportDialog"
    :modal-append-to-body="true"
    :close-on-click-modal="false"
    :visible.sync="showImportDialog"
    @close="handleImportReset"
  >
    <avue-form
      class="import-form"
      ref="importRef"
      v-model="importDialog.form"
      :option="importDialog.option"
      @submit="handleImportSubmit"
      :upload-before="uploadBefore"
      @reset-change="handleImportReset"
    >
      <template slot="excelFile">
        <el-upload
          ref="excelFile"
          class="importConfigDialog"
          drag
          action="#"
          accept=".xlsx,.xls"
          limit="1"
          :auto-upload="false"
          :before-remove="handleBeforeRemove"
          :on-change="uploadBefore"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            <div>请上传 .xlsx,.xls标准格式文件</div>
          </div>
        </el-upload>
      </template>
      <template slot="excelTemplate">
        <el-button :loading="loading" type="primary" class="el-icon-download el-icon--right" @click="handleTemplate()">模板下载</el-button>
      </template>
    </avue-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" icon="el-icon-check" v-preventReClick @click="handleSubmit">保存</el-button>
      <el-button size="small" icon="el-icon-delete" @click="handleReset">取消</el-button>
    </span>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </el-dialog>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters } from 'vuex';
import { getToken } from '@/util/auth';
import { getExprot } from '@/api/repair/failureconfig';
import { importData } from '@/api/product/productSerialNumManage';
export default {
  components: {
    GlobalModalTemplate
  },
  props: {
    showImportDialog: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    importType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      importDialog: {
        form: {},
        option: {
          searchShow: true,
          searchMenuSpan: 6,
          menuPosition: 'right',
          submitBtn: false,
          labelWidth: 150,
          emptyBtn: false,
          column: [
            {
              label: '序列号规则',
              prop: 'sequenceDefinitionName',
              type: 'search',
              disabled: true,
              appendClick: () => {
                this.openSequenceDefinitionModal();
              },
              control: (val, form) => {
                if (this.importType === 'regeneratedSN') {
                  return {
                    sequenceDefinitionName: { display: true }
                  };
                } else {
                  return {
                    sequenceDefinitionName: { display: false }
                  };
                }
              },
              rules: [
                {
                  required: true,
                  message: '请选择序列号规则',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '附件上传',
              prop: 'excelFile',
              span: 24,
              drag: true,
              type: 'upload',
              loadText: '附件上传中，请稍等',
              propsHttp: {
                res: 'data'
              },
              data: {},
              headers: {
                'Blade-Auth': getToken()
              },
              accept: '.xlsx,.xls',
              tip: '请上传.xls,.xlsx标准格式文件',
              action: '#'
              // action: '/api/blade-resource/oss/endpoint/put-file-attach'
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24
            }
          ]
        }
      },
      // form: {},
      query: {},
      cloneForm: {},
      loading: false,
      selectionList: [],
      data: [],
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  mounted() {},
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.smttable_add, false),
        viewBtn: this.vaildData(this.permission.smttable_view, false),
        delBtn: this.vaildData(this.permission.smttable_delete, false),
        editBtn: this.vaildData(this.permission.smttable_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    title() {
      const titleMap = { outSn: '外部序列号导入', outPackSN: '外部包装条码导入', regeneratedSN: '预生成序列号导入' };
      return titleMap[this.importType];
    }
  },
  methods: {
    handleImport() {
      this.showImportDialog = true;
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          this.cloneForm = this._cloneDeep(res.data.data);
        });
      }
      if (['add', 'edit'].includes(type)) {
      }
      done();
    },
    async handleTemplate() {
      try {
        this.loading = true;
        const codeMap = {
          outSn: {
            exportName: '外部产品序列号导入模板.xlsx',
            exportCode: 'OUTER_SN_IMPORT_TEMPLATE'
          },
          outPackSN: {
            exportName: '外部包装条码导入模板.xlsx',
            exportCode: 'OUTER_PACKING_SN_IMPORT_TEMPLATE'
          },
          regeneratedSN: {
            exportName: '预生成序列号导入模板.xlsx',
            exportCode: 'POOL_SN_IMPORT_TEMPLATE'
          }
        };
        const res = await getExprot(codeMap[this.importType].exportCode);
        const blob = new Blob([res.data]);
        const fileName = codeMap[this.importType].exportName;
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        const failMsg = await this.blobToJson(e.data);
        this.$message.error(failMsg.msg);
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async blobToJson(blob) {
      return new Promise((resolve, reject) => {
        blob.arrayBuffer().then(
          async (arrayBuffer) => {
            resolve(JSON.parse(Buffer.from(arrayBuffer).toString('utf-8')));
          },
          (error) => {
            reject(error);
          }
        );
      });
    },
    openSequenceDefinitionModal() {
      this.visibile = true;
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?isPregenerated=true&type=material&subType=work_in_progress',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      this.importDialog.form.sequenceDefinitionCode = rowData.code || '';
      this.importDialog.form.sequenceDefinitionId = rowData.id || '';
      this.importDialog.form.sequenceDefinitionName = rowData.name || '';
      this.visibile = false;
    },
    // 导入保存
    handleSubmit() {
      this.$refs.importRef.submit();
    },
    // 导入取消
    handleReset() {
      this.$refs.importRef.resetForm();
    },
    async handleImportSubmit(form, done) {
      await this.importData(form);
      done();
    },

    async importData(form) {
      try {
        if (!this.importDialog.form.file || this.importDialog.form.file.length === 0 || !this.importDialog.form.file.uid) {
          this.$message.warning('请先上传文件后再操作！');
          return;
        }
        let fileParams = new FormData();
        Object.keys(form).forEach((item) => {
          if (form[item]) {
            fileParams.append(item, form[item]);
          }
        });
        const interfaceMap = {
          outSn: '/api/mes-admin/label-product/import/outer/sn',
          outPackSN: '/api/mes-warehouse/packing/import/outer/sn',
          regeneratedSN: '/api/mes-admin/sequence/pool/import'
        };
        const res = await importData(interfaceMap[this.importType], fileParams);
        this.$message.success(res.data.msg);
        this.$emit('closeImportDialog');
        this.showImportDialog = false;
        this.$refs.importRef.resetFields();
      } catch (e) {
        console.warn(e);
      } finally {
        this.importDialog.form.file = {};
        this.$refs.excelFile.clearFiles();
      }
    },
    uploadBefore(file) {
      let nameArray = file.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importDialog.form.file = file.raw;
      } else {
        this.$message({
          message: '文件格式错误,请确认文件内容并重新上传',
          type: 'warning',
          duration: 2000
        });
      }
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importDialog.form.file = {};
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    handleImportReset() {
      this.showImportDialog = false;
      this.$refs.importRef.resetForm();
      this.$emit('closeImportDialog');
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .smtStandDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
  .avue-form__menu--right {
    display: none;
  }
  .detailTitle {
    font-size: 16px;
    font-weight: bold;
    height: 50px;
    line-height: 50px;
    color: rgba(0, 0, 0, 0.85);
    border-bottom: 1px solid #eee;
  }
  .detailArea {
    .avue-crud__menu {
      display: none;
    }
  }
}
::v-deep .replaceMateriaDialog {
  .row {
    display: flex;
    .deleteIcon {
      margin-left: 10px;
    }
  }
  .addIcon {
    display: flex;
    justify-content: center;
  }
  .avue-crud__menu {
    display: none;
  }
}
.import-form {
  margin-top: 16px;
}
</style>
